package com.dogkr.server.web.guest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.dogkr.common.Constants;
import com.dogkr.server.entity.User;
import com.dogkr.server.service.UserService;
import com.sean.common.action.BaseAction;
import com.sean.common.action.BaseAction.PageResult;
import com.sean.common.utils.StringUtils;


// 设置Struts2注解
@ParentPackage(value = "project-default")
@Namespace(value = "/reg")
@ResultPath("/WEB-INF/jsps")
// 页面文件空间
@Results({
	@Result(name = "index", location = "index.jsp")
})
public class RegAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	
	private User user;
	
	@Autowired
	private UserService userService;
	
	@Action(value="reg")
	public String regIndex() {
		
		return "index";
	}
	
	//用户注册
	@Action(value="regSave")
	public void register() {
		try { 
			if(user != null) {
				if(StringUtils.isNotBlank(user.getLoginName(), user.getLoginPassword()) ) {
					user.setLoginName(user.getLoginName().toLowerCase());
					user.setLoginPassword(DigestUtils.md5Hex(user.getLoginPassword()));
					user.setUserEmail(user.getLoginName());
					userService.register(user);
					User loginUser = userService.selectByLoginName(user.getLoginName());
					this.getSessiont().setAttribute(Constants.LOGIN_USER_KEY, loginUser);
				} else {
					res = this.getErrRes();
				}
			} else {
				res = this.getErrRes();
			}
		} catch (Exception e) {
			log.error("注册失败." + user, e);
		}
		outJson(res);
	}
	
	//账号查询
	@Action(value="check")
	public void checkLonginName() {
		String loginName = this.get("loginName");
		if(userService.checkLonginName(loginName)) {
			res = this.getErrRes("用户名已存在.");
		}
		outJson(res);
	}
	
	

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
}
